﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using ZHDJ.BranchCenter.BLL;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.Center;
using ZHDJ.WebPage;

namespace ZHDJ.BranchCenter.Module.PartyRepresentative
{
    public partial class PartyRepresentativeMeetingEdit : PageBase
    {
        #region 属性
        /// <summary>
        /// 是否和个人中心共用
        /// </summary>
        public override bool IsCommonPage
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// 工作室ID
        /// </summary>
        public string StudioID
        {
            get
            {
                return GetQueryIntValue("StudioID"); ;
            }
        }
        #endregion
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get { return "PartyRepresentativeMeetingAdd"; }
        }

        #endregion

        #region 页面属性

        public string EditorContent { get; set; }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        private void BindData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            //工作室加载
            ControlBusiness.ControlBind(
                ddlStudio, DB.PartyRepresentativeStudios.OrderBy(a => a.CreateTime),
                "StudioName", "ID");
            ddlStudio.SelectedValue = StudioID;
            //党代表加载 
            ControlBusiness.ControlBind(cblJoinRepresentative, DB.PartyRepresentativeInfos.Where(a=>a.StudioID==StudioID).OrderBy(a => a.OrderNo),"UserName", "ID");
            if (IsSystemAdmin)
            {
                this.ddlStudio.Readonly = false;
            }
            else
            {
                this.ddlStudio.Readonly = true;
            }
        }

        private void LoadData()
        {
            if (string.IsNullOrEmpty(StudioID))
            {
                Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                return;
            }
            string id = GetQueryIntValue("id");
            if (id != "")
            {
                var current = DB.PartyRepresentativeMeetings.Find(id);
                if (current == null)
                {
                    // 参数错误，首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                txtAddress.Text = current.Address;
                txtTitle.Text = current.Title;
                ddlStudio.SelectedValue = current.StudioID;
                dtBeginDate.Text = Convert.ToDateTime(current.BeginTime).ToString("yyyy-MM-dd HH:mm");
                dtEndDate.Text = Convert.ToDateTime(current.EndTime).ToString("yyyy-MM-dd HH:mm");
                cbxEnabled.Checked = current.Status == 4;
                EditorContent = current.Content;
                LoadSelectRepresentative(id);
            }
            else
            {
                dtBeginDate.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 09:00");
                dtEndDate.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 16:00");
            }
        }

        /// <summary>
        /// 加载已选择的党代表
        /// </summary>
        /// <param name="meetingId"></param>
        public void LoadSelectRepresentative(string meetingId)
        {
            var q = DB.PartyRepresentativeMeetingJoins.Where(a => a.MeetingID == meetingId);
            foreach (var item in q)
            {
                foreach (var joinitem in cblJoinRepresentative.Items)
                {
                    if (joinitem.Value == item.RepresentativeID)
                    {
                        joinitem.Selected = true;
                        break;
                    }
                }
            }
        }


        /// <summary>
        /// 保存已选择的党代表
        /// </summary>
        /// <param name="meetingId"></param>
        public void SaveSelectRepresentative(string meetingId)
        {
            //删除已选择
            DB.PartyRepresentativeMeetingJoins.Where(t => t.MeetingID == meetingId).ToList().ForEach(t => DB.PartyRepresentativeMeetingJoins.Remove(t));
            var q = DB.PartyRepresentativeMeetingJoins.Where(a => a.MeetingID == meetingId);
            foreach (var item in cblJoinRepresentative.Items)
            {
                if(!item.Selected) continue;
                var join = new PartyRepresentativeMeetingJoin();
                join.ID = StringHelper.NewID;
                join.MeetingID = meetingId;
                join.RepresentativeID = item.Value;
                DB.PartyRepresentativeMeetingJoins.Add(join);
                DB.SaveChanges();

            }
        }
        #endregion

        #region Events

        private void SaveData()
        {
            if (string.IsNullOrEmpty(StudioID))
            {
                Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                return;
            }
            if (Convert.ToDateTime(dtBeginDate.Text) > Convert.ToDateTime(dtEndDate.Text))
            {
                Alert.Show("开始时间不能大于结束时间！", String.Empty);
                return;
            }
            string id = GetQueryIntValue("id");
            string imageUrl = string.Empty;
            PartyRepresentativeMeeting editModel;
            if (id != "")
            {
                //更新
                editModel = DB.PartyRepresentativeMeetings.Find(id);
                if (editModel == null)
                {
                    Alert.Show("参数错误！", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                editModel.ModifyTime = DateTime.Now;
                editModel.ModifyBy = CurrentUser.LoginID;
            }
            else
            {
                editModel = new PartyRepresentativeMeeting();
                editModel.ID = StringHelper.NewID;
                editModel.CreateTime = DateTime.Now;
                editModel.ModifyTime = DateTime.Now;
                editModel.CreateBy = CurrentUser.LoginID;
                editModel.ModifyBy = CurrentUser.LoginID;
                editModel.OrderNo = DB.PartyRepresentativeMeetings.Count() + 1;
                DB.PartyRepresentativeMeetings.Add(editModel);
            }

            editModel.StudioID = StudioID;
            editModel.Content= this.Request.Form["editorValue"];
            editModel.Address = txtAddress.Text;
            editModel.Title = txtTitle.Text;
            editModel.BeginTime = Convert.ToDateTime(dtBeginDate.Text);
            editModel.EndTime = Convert.ToDateTime(dtEndDate.Text);
            editModel.Status = cbxEnabled.Checked ? 4 : 1;
            if (DB.SaveChanges() > 0)
            {
                SaveSelectRepresentative(editModel.ID);
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            }

        }

        /// <summary>
        /// 保存并关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData();

            
        }


        #endregion
        
    }
}